﻿namespace Lilium.Web

module HttpApplication =
    
    open  System

    open Lilium.Prelude

    // registers resource which shoud be disposed after request processing completion
    // context  - http current context
    // resource - disposable resource
    // returns subscription as IDisposable object. User can call use the Dispose() method to unsubsribe.
    // in this case object will not dispose.
    let registerDisposableResource (context : System.Web.HttpContextBase) (resource : IDisposable) =
        
        let finishEvent = Observable.merge context.ApplicationInstance.EndRequest context.ApplicationInstance.Error
        
        let subscribe = lazyFix (fun (subscription : IDisposable Lazy) -> finishEvent.Subscribe (fun _ -> 
            resource.Dispose() 
            subscription.Value.Dispose()))

        subscribe ()